package com.openNetty.common.utils;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.util.Map;
import java.util.Random;

/**
 * DES加解密工具类
 *
 * @author zhenggm
 */
public class EncryptUtil {
    private static final Logger log = LogManager.getLogger(EncryptUtil.class);

    /**
     * 加密逻辑方法
     *
     * @param message
     * @param key
     * @return
     * @throws Exception
     */
    private static byte[] encryptProcess(String message, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return cipher.doFinal(message.getBytes("UTF-8"));
    }

    /**
     * 解密逻辑方法
     *
     * @param message
     * @param key
     * @return
     * @throws Exception
     */
    private static String decryptProcess(String message, String key) throws Exception {
        byte[] bytesrc = convertHexString(message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte);
    }

    /**
     * 16进制数组数转化
     *
     * @param ss
     * @return
     */
    private static byte[] convertHexString(String ss) throws Exception {
        byte[] digest = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }
        return digest;
    }

    /**
     * 十六进制数转化
     *
     * @param b
     * @return
     * @throws Exception
     */
    private static String toHexString(byte[] b) throws Exception {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2) {
                plainText = "0" + plainText;
            }
            hexString.append(plainText);
        }

        return hexString.toString();
    }

    /**
     * 加密方法
     */
    public static String encrypt(String message, String key) {
        log.debug("加密原串为：" + message);
        if (message == null) {
            return null;
        }
        String enStr = null;
        try {
            String orignStr = java.net.URLEncoder.encode(message, "utf-8");
            enStr = toHexString(encryptProcess(orignStr, key));
        } catch (Exception e) {
            log.error("参数加密异常！", e);
        }
        return enStr;
    }


    /**
     * 译码
     *
     * @param str 要译码的字符串
     * @return 译码后的字符串
     */
    public static String encode(String str) {
        StringBuilder sb = new StringBuilder();
        int n = str.length();
        char c = 0;
        int k = 0;
        for (int i = 0; i < n; i++) {
            // 获得当前字符
            c = str.charAt(i);
            // c是1-9的数字, 且i<n-1   复制(k+1)次后面的一个字符
            if (c >= '1' && c <= '9' && i != n - 1) {
                k = c - '0' + 1;
                for (int j = 0; j < k; j++) {
                    sb.append(str.charAt(i + 1));
                }

            } else if (c == '_') {
                // c除1-9，且为”_”转换为”\Ul”
                sb.append("\\UL");
            } else {
                //其余复制该字符
                sb.append(c);
            }
            sb.append("_");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    /**
     * 解码
     *
     * @param str 要解码的字符串
     * @return 解码后的字符串
     */
    public static String decode(String str) {
        StringBuilder sb = new StringBuilder();
        String[] strs = str.split("_");
        char c = 0;
        int k = 0;
        int n = strs.length;
        if (n == 1) {
            sb.append(str);
        } else {
            for (int i = 0; i < n; i++) {
                k = strs[i].length();
                c = strs[i].charAt(0);
                if (1 == k) {
                    // k==1,  将该字符原样复原
                    sb.append(c);
                } else {
                    //　　k>1,
                    if ("\\UL".equals(strs[i])) {
                        // strs[i] == ”\Ul”,  转换为”_”
                        sb.append("_");
                    } else {
                        // strs[i] != ”\Ul”,  转换为k(k = strs[i].length()-1)
                        sb.append(k - 1);
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * 解密方法
     */
    public static String decrypt(String message, String key) {
        log.debug("解密内容为" + message);
        String decStr = null;
        if (message == null) {
            return null;
        }
        try {
            decStr = java.net.URLDecoder.decode(decryptProcess(message, key), "utf-8");
        } catch (Exception e) {
            log.error("参数解密异常！", e);
        }
        return decStr;
    }

    /**
     * DES加密
     * @param keystr 秘钥文本
     * @param bt 加密数组
     * @return
     */
    public static byte[] DESedeEncByte(String keystr, byte bt[]) {
        try {
            byte[] keybyte = HexBin.decode(keystr);
            DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(keybyte);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
            Key key = secretKeyFactory.generateSecret(deSedeKeySpec); //获取到key秘钥

            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(bt);
        } catch (Exception e) {
            log.error("加密异常：" + e.getMessage());
        }
        return null;
    }

    /**
     * DES加密
     * @param keystr 秘钥文本
     * @param bt 加密数组
     * @return
     */
    public static byte[] DESedeDecByte(String keystr, byte bt[]) {
        try {
            byte[] keybyte = HexBin.decode(keystr);
            DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(keybyte);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
            Key key = secretKeyFactory.generateSecret(deSedeKeySpec); //获取到key秘钥

            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(bt);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("加密异常：" + e.getMessage());
        }
        return null;
    }

    /**
     * 获取随机秘钥键值
     *
     * @return
     */
    public static String getKey(Map<String, String> map) {
        String[] keys = map.keySet().toArray(new String[0]);
        Random random = new Random();
        String randomKey = keys[random.nextInt(keys.length)];
        return randomKey;
    }
}